package com.example.demo.controller;

import com.example.demo.config.JwtTokenUtil;
import com.example.demo.config.UnauthorizedException;
import com.example.demo.model.JwtRequest;
import com.example.demo.model.JwtResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("authenticate")
public class JwtAuthenticationController {

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {

        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        final String token = JwtTokenUtil.sign(authenticationRequest.getUsername());
        return ResponseEntity.ok(new JwtResponse(token));
    }

    private void authenticate(String username, String password) {
        if (username.equals("user") && password.equals("password")) {

        } else {
            throw new UnauthorizedException("Bad username or password");
        }
    }

}